package com.hzit.boot.controller;

import com.hzit.boot.entity.Classes;
import com.hzit.boot.entity.PageResult;
import com.hzit.boot.entity.R;
import com.hzit.boot.entity.Student;
import com.hzit.boot.service.ClassesService;
import com.hzit.boot.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hbxfwf
 * @since 2023-06-01
 */
@Controller
@RequestMapping("/student")
public class StudentController {
	@Autowired
	private StudentService studentService;
	@Autowired
	private ClassesService classesService;
	//1. 查询所有学生
	@GetMapping("/list")
	public String findAll(Model model){
		//1.1 查询所学生
		List<Student> studentList = studentService.findAll();
		//1.2 将学生放到model中
		model.addAttribute("students",studentList);
		//1.3 页面跳转
		return "student/list";  //真实的物理路径： templates/student/list.html
	}

	//2. 分页
	@GetMapping("/findByPage")
	public String findByPage(@RequestParam(required = false,defaultValue = "1") int page,
	                         @RequestParam(required = false,defaultValue = "5") int pageSize,
	                         Model model){
		//2.1 查询分页的学生信息
		PageResult<Student> pageResult = studentService.findByPage(page,pageSize);
		model.addAttribute("pr",pageResult);
		return "student/list";
	}

	//3. 分页条件查询
	@RequestMapping("/search")
	public String search(@RequestParam(required = false,defaultValue = "1") int page,
                         @RequestParam(required = false,defaultValue = "5") int pageSize,
                         Student student,
                         Model model){
		//3.1 查询分页的学生信息
		PageResult<Student> pageResult = studentService.search(page,pageSize,student);
		model.addAttribute("pr",pageResult);
		//3.2 查询所有班级列表
		List<Classes> classes = classesService.findAll();
		model.addAttribute("classes",classes);
		model.addAttribute("student",student);
		System.out.println("student = " + student);
		return "student/list";
	}

	//4. 添加学生
	@PostMapping("/add")
	public String add(Student stud){
		//4.1 添加学生
		studentService.add(stud);
		//4.2 重定向到学生列表
		return "redirect:/student/search";
	}

	//5. 修改学生
	@PostMapping("/update")
	public String update(Student stud){
		//4.1 修改学生
		studentService.update(stud);
		//4.2 重定向到学生列表
		return "/student/search";  //相当于：response.sendRedirect('/student/search')
	}

	//6. 删除学生
	@GetMapping("/delete")
	public String delete(String sid){
		studentService.delete(sid);
		return "redirect:/student/search";
	}
}
